package cn.wildfirechat.remote;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * OSS图片上传的管理类
 */

public class OssManager {
    /**
     * 图片上传的地址
     * 问后台要的
     */
    public static String endpoint = "https://oss-xxxx.com";
    /**
     * 图片的访问地址的前缀
     * 其实就是： bucketName + endpoint
     */
    public static String prefix = "https://xxx.oss-xxxx.com/";
    /**
     * Bucket是OSS上的命名空间
     * 问后台要的
     */
    public static String bucketName = "xxx";

    /**
     * 图片保存到OSS服务器的目录，问后台要
     */
    public static String dir = "app/";

    private OSS mOSS;

    private static OssManager mInstance;
    private SharedPreferences sp;

    public static OssManager getInstance() {
        if (mInstance == null) {
            synchronized (OssManager.class) {
                mInstance = new OssManager();
            }
        }
        return mInstance;
    }

    /**
     * 创建OSS对象
     */
    private OSS getOSS(Context context) {
        if (mOSS == null) {
            sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
            endpoint = EncryptUtil.decryptAES(sp.getString("endpint", null), sp.getString("token", null));
            bucketName = EncryptUtil.decryptAES(sp.getString("bucket", null), sp.getString("token", null));
            prefix = "https://" + bucketName + "." + endpoint;
            OSSCredentialProvider provider = OSSConfig.newCustomSignerCredentialProvider(EncryptUtil.decryptAES(sp.getString("keyid", null), sp.getString("token", null)),
                    EncryptUtil.decryptAES(sp.getString("secret", null), sp.getString("token", null)));
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            mOSS = new OSSClient(context, endpoint, provider, conf);
        }
        return mOSS;
    }

    /**
     * 图片上传
     *
     * @param context
     * @param uploadFilePath   图片的本地路径
     * @param onUploadListener 回调监听
     * @param type             1为图片 2为视频 3为文件 4为头像
     */
    public void upload(final Context context, final int position, final String uploadFilePath,
                       final OnUploadListener onUploadListener, int type) {


        mOSS = getOSS(context);
        // 创建上传的对象
        PutObjectRequest put = new PutObjectRequest(bucketName,
                getUUIDByRules32Image(type)
                , uploadFilePath);
        // 上传的进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                if (onUploadListener == null) {
                    return;
                }
                onUploadListener.onProgress(position, currentSize, totalSize);
            }
        });
        mOSS.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                if (onUploadListener == null) {
                    return;
                }
                String imageUrl = request.getObjectKey();
                onUploadListener.onSuccess(position, uploadFilePath,
                        prefix + imageUrl);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
//                serviceException.printStackTrace();
//                clientException.printStackTrace();
                if (onUploadListener == null) {
                    return;
                }
                onUploadListener.onFailure(position);
            }
        });
    }


    public interface OnUploadListener {
        /**
         * 上传的进度
         */
        void onProgress(int position, long currentSize, long totalSize);

        /**
         * 成功上传
         */
        void onSuccess(int position, String uploadPath, String imageUrl);

        /**
         * 上传失败
         */
        void onFailure(int position);

    }

    /**
     * 上传到后台的图片的名称
     */
    public static String getUUIDByRules32Image(int type) {
        StringBuffer generateRandStr = null;
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date();
        try {
            String rules = "123456789";
            int rpoint = 0;
            generateRandStr = new StringBuffer();
            if (type == 1) {
                generateRandStr.append("pic/");
            } else if (type == 2) {
                generateRandStr.append("video/");
            } else if (type == 3) {
                generateRandStr.append("file/");
            } else if (type == 4) {
                generateRandStr.append("avatar/");
            } else if (type == 5) {
                generateRandStr.append("amr/");
            }
            generateRandStr.append(simpleFormat.format(now));
            generateRandStr.append("/" + now.getTime());
            Random rand = new Random();
            int length = 6;
            for (int i = 0; i < length; i++) {
                if (rules != null) {
                    rpoint = rules.length();
                    int randNum = rand.nextInt(rpoint);
                    generateRandStr.append(rules.substring(randNum, randNum + 1));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (generateRandStr == null) {
            return "getUUIDByRules32Image.png";
        }
        if (type == 1) {
            return generateRandStr + ".png";
        } else if (type == 2) {
            return generateRandStr + ".mp4";
        } else if (type == 3) {
            return generateRandStr + ".file";
        } else if (type == 4) {
            return generateRandStr + ".png";
        } else if (type == 5) {
            return generateRandStr + ".amr";
        } else {
            return generateRandStr + ".file";
        }
    }
}